package chapter02;

import java.util.Arrays;

/**
 * 主要元素
 */
public class Q26 {


    public static void main(String[] args) {
        int[] arr = {3, 3, 4, 2, 4, 4, 2, 4, 4};
        int majorityElement = new Q26().majorityElement(arr);
        System.out.println(majorityElement);
    }

    public int majorityElement(int[] nums) {
        Arrays.sort(nums);
        int majorityElement = nums[nums.length / 2];
        int number = 0;
        for (int num: nums) {
            if (num == majorityElement) {
                number++;
            }
        }
        if(number > nums.length / 2) {
            return majorityElement;
        }
        return -1;
    }
}
